package com.example.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    private static Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private CaptchaProperties captchaProperties;
    //一分钟的毫秒数
    private static long VALID_TIME_OUT = 60 * 1000;
    @RequestMapping("/getCaptcha")
    public void getCaptch(HttpServletResponse response,HttpSession session) {
        //生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //打印验证码
        String code = lineCaptcha.getCode();
        System.out.println("System生成验证码" + code);
        logger.info("Logger生成验证码" + code);
        //存储session
        session.setAttribute(captchaProperties.getSession().getKey(),code);
        session.setAttribute(captchaProperties.getSession().getDate(),new Date());
        //把验证码写到浏览器
        try {
            lineCaptcha.write(response.getOutputStream());
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("utf-8");
            //防止缓存
            response.setHeader("Pragma","No-cache");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/check")
    public boolean check(String captcha,HttpSession session){
        System.out.println("用户输入验证码：" + captcha);
        if(!StringUtils.hasLength(captcha))
            return false;
        String code = (String)session.getAttribute(captchaProperties.getSession().getKey());
        Date date = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        //校验captcha是否正确
        if(date == null || System.currentTimeMillis() - date.getTime() > VALID_TIME_OUT)
            return false;
        return captcha.equalsIgnoreCase(code);
    }
}
